import 'dart:convert';

import 'package:event_bus/event_bus.dart';
import 'package:get/get.dart';
import 'package:wk_robot2/app/blt/RobotCommandsHelper.dart';
import 'package:wk_robot2/app/event/MsgContentEvent.dart';
import 'package:wk_robot2/app/logger/Logger.dart';
import 'package:wk_robot2/app/nets/NetWorkManager.dart';
import 'package:wk_robot2/app/utils/CommonUtil.dart';
import 'package:wk_robot2/app/widget/tips.dart';


import '../../../blt/protobuf/BleBindOrSwitchWifi.pb.dart';
import '../../../blt/protobuf/BluetoothHandShake.pb.dart';
import '../../../const/AppConst.dart';
import '../../../event/DataCallBack.dart';
import '../../../routes/app_pages.dart';
import '../../bindtip/views/bindtip_view.dart';

class ConnectSucessController extends GetxController {
  var pageTip = '蓝牙配对成功'.obs;

  @override
  void onInit() {
    super.onInit();
    // BltManager.instance.scanDevices();
  }

  @override
  void onReady() {
    super.onReady();
    // 先检查Robot是否已经被绑定,没有在走下面的逻辑.
    checkWhetherRobotHasBind();
  }

  void checkWhetherRobotHasBind() {
      NetWorkManager.getInstance().requestBussiness(NetWorkManager.ROBOT_GET_BINDUSERS+"", {
         'robotUserId': CommonUtil.getBltDeviceTmpSN()
      }, NetWorkManager.methodGET, DataCallBack(
        businessCallBack: (v) {
          if (v.length > 0) {
               Map item = v[0];
               if (item['userId'] == CommonUtil.getLoginUserId()) {
                  Tips.showToast('你已绑定此机器人');
                  Future.delayed(Duration(seconds: 2),() {
                    Get.offAllNamed(Routes.HOME);
                  });

               } else {
                 item['robotUserId'] = CommonUtil.getBltDeviceTmpSN();
                 item['type'] = ERROR_BINDING_ACCOUNT;
                 Get.offNamed(Routes.BINDTIP,arguments: item);
               }
          } else {
            checkNetRobotNetWork();
          }
        },
        errorCallBack:(v) {
          Get.toNamed(Routes.BINDTIP,arguments: {
            'type': DEVICE_SN_NO_EXISTANCE,
            'robotUserId': CommonUtil.getBltDeviceTmpSN()
          });
        }
      ));


  }

  void checkNetRobotNetWork() {
    logger.info('检查机器人网络前,第一次握手.');
    Future.delayed(Duration(seconds: 1),() {
      RobotCommandsHelper().shakeHandWithRobot(DataCallBack(
          deviceCallBack: (data) {
            // BluetoothShakeResponse response = BluetoothShakeResponse.fromBuffer(data[AppConst.BTL_DATA_KEY]);
            logger.info('第一次握手成功,BL_NEW_HAND_SHAKE_REQUEST');

            //检查robot是否有网络.
            pageTip.value = '正在检查悟空Wi-Fi连接 ...';

            Future.delayed(Duration(milliseconds: 5000),() {

              RobotCommandsHelper().sendHandShake(DataCallBack(
                  deviceCallBack: (data) {
                    // BindOrSwitchWifiResponse sendHandShakeResponse  = BindOrSwitchWifiResponse.fromBuffer(data[AppConst.BTL_DATA_KEY]);
                    logger.info('第二次发送握手成功 BL_BIND_OR_SWITCH_WIFI_REQUEST');

                    // 这时候可以显示配对成功.

                    Future.delayed(Duration(milliseconds: 5000),() {
                      RobotCommandsHelper().sendWifiIsOkMsgToRobot(DataCallBack(deviceCallBack: (data) {
                        if (data != null) {
                          BindOrSwitchWifiResponse wifiResponse = BindOrSwitchWifiResponse.fromBuffer(data[AppConst.BTL_DATA_KEY] as List<int>);
                          logger.info('机器人wifi状况 ==========> ' + wifiResponse.data);

                          Map<String,dynamic> wifiData = json.decode(wifiResponse.data);
                          if (wifiData['cd'] == 1 && wifiData['wsc'] == '1') { // 已经有配网.
                            Get.offNamed(Routes.BINDING);
                          } else {
                            Get.offNamed(Routes.WIFI_SETTING);
                          }

                          // Get.offNamed(Routes.WIFI_SETTING);

                          // Get.toNamed(Routes.WIFI_SETTING);

                        } else {
                          logger.info('机器人网络检查失败.');

                        }

                      }));

                    });


                  }
              ));
            });
          }
      ));

    });
  }

  @override
  void onClose() {
    super.onClose();
  }
}
